using AutoMapper;
using BackData;
using Domain.BOM;
using Domain.DTOs.Order;
using Domain.生产订单;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Order;

namespace Team.API.Applocation.Hanldler.Order
{
    /// <summary>
    /// 查询订单列表命令处理器
    /// </summary>
    public class GetOrderListHandler : IRequestHandler<GetOrderListCommand, APIResult<List<OrderDTO>>>
    {
        private readonly IMapper _mapper;
        private readonly IRepository<OrderModel> _orderRep;
        private readonly IRepository<Bomtable> _bomRep;
        private readonly ILogger<GetOrderListHandler> _logger;

        public GetOrderListHandler(
            IMapper mapper,
            IRepository<OrderModel> orderRep,
            IRepository<Bomtable> bomRep,
            ILogger<GetOrderListHandler> logger)
        {
            _mapper = mapper;
            _orderRep = orderRep;
            _bomRep = bomRep;
            _logger = logger;
        }

        public async Task<APIResult<List<OrderDTO>>> Handle(GetOrderListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有未删除的订单
                var query = _orderRep.GetAll().Where(x => !x.IsDel);

                // 按成品编号筛选
                if (request.Itemcode.HasValue)
                {
                    query = query.Where(x => x.Itemcode == request.Itemcode.Value);
                }

                // 按订单状态筛选
                if (request.Orderstatus.HasValue)
                {
                    query = query.Where(x => x.Orderstatus == request.Orderstatus.Value);
                }

                // 按时间范围筛选
                if (request.StartTime.HasValue)
                {
                    query = query.Where(x => x.Ordertime >= request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    query = query.Where(x => x.Ordertime <= request.EndTime.Value);
                }

                var list = await query.OrderByDescending(x => x.Ordertime).ToListAsync();

                // 获取所有相关的成品信息
                var itemcodes = list.Select(x => x.Itemcode).Distinct().ToList();
                var items = await _bomRep.GetAll()
                    .Where(x => itemcodes.Contains(x.Id) && !x.IsDel)
                    .ToListAsync();

                var itemDict = items.ToDictionary(x => x.Id, x => x.Goodsname);

                // 映射为DTO
                var resultDTOs = list.Select(order =>
                {
                    var dto = _mapper.Map<OrderDTO>(order);
                    dto.Itemname = itemDict.ContainsKey(order.Itemcode)
                        ? itemDict[order.Itemcode]
                        : "未知成品";
                    dto.OrderstatusText = GetOrderstatusText(order.Orderstatus);
                    return dto;
                }).ToList();

                _logger.LogInformation($"查询到 {resultDTOs.Count} 条订单记录");

                return new APIResult<List<OrderDTO>>
                {
                    Code = StateCode.OK,
                    Message = "订单查询成功",
                    Result = resultDTOs
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "订单查询失败");
                return new APIResult<List<OrderDTO>>
                {
                    Code = StateCode.Fail,
                    Message = $"订单查询失败: {ex.Message}",
                    Result = new List<OrderDTO>()
                };
            }
        }

        private string GetOrderstatusText(int status)
        {
            return status switch
            {
                0 => "待排程",
                1 => "已排程",
                2 => "生产中",
                3 => "已完成",
                4 => "已取消",
                _ => "未知状态"
            };
        }
    }
}
